
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';

import 'api.dart';
import 'dart:convert' as convert;
//域名(填写自己的)
final baseUrl = 'http://xxx.com/';

final Http  http =  Http();
//http 请求子类
class Http extends BaseHttp{
     @override
  void init() {
    options.baseUrl = baseUrl;
    options.connectTimeout  =  1000 * 45; //连接超时时间
    options.receiveTimeout = 1000 * 45; //响应超时时间
    interceptors..add(ApiInterceptor());
  }
}

class ApiInterceptor  extends  InterceptorsWrapper {
       @override
       onRequest(RequestOptions options) async{
         var data  = options.data;
         if(data ==null){
           data = Map<String,dynamic>();
         }
         //json序列化
         if (data is  Map){
           //自定义请求参数
           //例如所有接口需要一个签名字段
//             data["sign"] = "sas111111";
            options.data  = convert.jsonEncode(data);
         }else{
            options.data = convert.jsonEncode(data);
         }
         return  options;
     }
     //对服务器返回做一层统一处理
      @override
     onResponse(Response response)  async{
        debugPrint(
            '<-- ${response.statusCode} ${response.request.baseUrl}${response.request.path}');
        debugPrint('<-- ${response.data.toString()}');
        debugPrint('<-- END HTTP(${response.toString().length}byte)');

         ResponseData responseData  =  ResponseData.fromJson(response.data);
         if(responseData.sucess){
           response.data = responseData.data; //返回后端给的有效数据
           return http.resolve(response);
         }else{
//           前面自定义的Exception（有其他的都可以自己抛出来）
           throw NotSuccessException.fromResponData(responseData);
         }

     }
}

//根据后端自定义（只举例说明）
class ResponseData extends BaseResponseData{

      bool get sucess => 1 == state;
      ResponseData.fromJson(Map json) {
         state =  json ["state"];
         msg = json["msg"];
         data  = json["data"];
      }
}